package bll

import (
	"encoding/json"
	"lutai/src/util"
	"strings"
)

// Packet 业务处理
type Packet struct {
	*Bll
}

// QueryPage 查询
func (p *Packet) QueryPage(page, pageSize int) (map[string]interface{}, error) {

	datas, err := p.Models.Packet.QueryPage(page, pageSize)
	if err != nil {
		return nil, err
	}
	for _, data := range datas {
		data.CreateTime = util.UnixNanoFormat(data.Created)
		data.UpdateTime = util.UnixNanoFormat(data.Updated)
	}

	count, err := p.Models.Packet.QueryCount()
	if err != nil {
		return nil, err
	}
	results := map[string]interface{}{
		"total": count,
		"data":  datas,
	}
	return results, nil
}

// QueryData 查询数据包
func (p *Packet) QueryData(id string) ([]interface{}, error) {
	datas, err := p.Models.Packet.GetPacketData(id)
	if err != nil {
		return nil, err
	}

	results := make([]interface{}, 0, 0)
	switch datas.PkgType {
	default:
		d := strings.Split(datas.Data, ",")
		for k, v := range d {
			r := make(map[string]interface{})
			switch datas.PkgType {
			case 51, 52, 53, 54, 55, 56:
				r["Key"] = util.Get5_123456(k + 1)
			case 58:
				r["Key"] = util.Get58(k + 1)
			case 60:
				r["Key"] = util.Get60(k + 1)
			case 61:
				r["Key"] = util.Get61(k + 1)
			}

			if r["Key"] == "" {
				continue
			}

			r["Value"] = v
			results = append(results, r)
		}
	case 200:
		d := make(map[string]interface{})
		err = json.Unmarshal([]byte(datas.Data), &d)
		if err != nil {
			return nil, err
		}
		results = append(results, d)
	}

	return results, nil
}
